package com.practice.springboot_01_zwj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.practice.springboot_01_zwj.entity.AssignedTask;
import com.practice.springboot_01_zwj.entity.dto.AssignedTaskResponse;
import com.practice.springboot_01_zwj.mapper.AssignedTaskMapper;
import com.practice.springboot_01_zwj.service.AssignedTaskService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class AssignedTaskServiceImpl implements AssignedTaskService {

    @Autowired
    private AssignedTaskMapper assignedTaskMapper;

    @Override
    public int addAssignedTask(AssignedTask assignedTask) {
        return assignedTaskMapper.addAssignedTask(assignedTask);
    }

    @Override
    public int updateAssignedTask(AssignedTask assignedTask) {
        return assignedTaskMapper.updateAssignedTask(assignedTask);
    }

    @Override
    public int deleteAssignedTask(Integer id) {
        return assignedTaskMapper.deleteAssignedTask(id);
    }

    @Override
    public AssignedTaskResponse selectAssignedTask(String proposeLeader,
                                                   String finishState,
                                                   String deptName,
                                                   int pageNum,
                                                   int pageSize) {
        // 1. 参数校验
        if (pageNum < 1) pageNum = 1;
        if (pageSize < 1 || pageSize > 100) pageSize = 10;

        // 2. 处理空字符串情况
        if (proposeLeader != null && proposeLeader.isEmpty()) {
            proposeLeader = null;
        }
        if (finishState != null && finishState.isEmpty()) {
            finishState = null;
        }
        if (deptName != null && deptName.isEmpty()) {
            deptName = null;
        }

        // 3. 启动分页
        PageHelper.startPage(pageNum, pageSize);

        // 4. 执行查询
        List<AssignedTask> tasks = assignedTaskMapper.selectAssignedTask(proposeLeader, finishState, deptName);
        PageInfo<AssignedTask> pageInfo = new PageInfo<>(tasks);

        // 5. 统计已完成和未完成数量
        Integer completedCount = assignedTaskMapper.countByFinishState(proposeLeader, "已完成", deptName);
        Integer uncompletedCount = assignedTaskMapper.countByFinishState(proposeLeader, "进行中", deptName);
        Integer totalCount = assignedTaskMapper.countByFinishState(proposeLeader, null, deptName);

        // 6. 返回响应对象
        return new AssignedTaskResponse(pageInfo, completedCount, uncompletedCount, totalCount);
    }

}